package NC;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class NC14 {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
        // write code here
        if(root==null) return new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>(); //临时存放取出的值，用于逆序输出
        boolean flag = true;  //标志是逆序还是顺序

        while (!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>(); //临时存放取出的值，用于逆序输出
            int size = queue.size();//现在在队伍中还有几个元素
            for (int i = 0; i < size; i++) {
                TreeNode node  = queue.poll();
                if(flag){
                    list.add(node.val);
                }else {
                    list.add(0,node.val);
                }
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);

            }
            flag = !flag;
            ans.add(list);
        }
        return ans;

    }

}
